import { UserService } from './user.service';
import { User, UserResponse } from './user.interface';
import { CreateUserDTO, EditUserDTO } from './user.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import {
    Body,
    Controller,
    Delete,
    Get,
    Param,
    Post,
    UseInterceptors,
    UploadedFile
} from '@nestjs/common';
import Multer from 'Multer';
const fs = require('fs');

@Controller('user')
export class UserController {
constructor(private readonly userService: UserService){}

    @Get('all')
    async findAll() : Promise<UserResponse<User[]>> {
        return {
            code: 200,
            data: await this.userService.findAll(),
            msg: 'success'
        }
    }

    @Get(':_id')
    async find(@Param('_id') _id: string) : Promise<UserResponse<User>> {
        return {
            code: 200,
            data: await this.userService.find(_id),
            msg: 'success'
        }
    }

    @Post('getby')
    async findWhere(@Body() filter?: object) : Promise<UserResponse<User[]>> {
        return {
            code: 200,
            data: await this.userService.findWhere(filter),
            msg: 'success'
        }
    }

    @Post('getID')
    async findUser(@Body() filter?: { code?: string}) : Promise<UserResponse<User[]>> {
        
        return {
            code: 200,
            data: await this.userService.findUser(filter),
            msg: 'success'
        }
    }

    @Post('add')
    async addone(@Body() body: CreateUserDTO) : Promise<UserResponse> {
        const res = await this.userService.find(body._id);
        if (!res){
            await this.userService.addone(body);
        } else {
            await this.userService.editone(body._id, body);
        }
        return {
            code: 200,
            msg: 'success'
        }
    }

    // 'file'必须与前端小程序uploadFile请求中的name保持一致
    @UseInterceptors(FileInterceptor('file'))
    @Post('upload')
    uploadFile(
        @Body() body: CreateUserDTO,
        @UploadedFile() file: Multer.File,
    ) {
        fs.writeFile('./imgs/test.png',file.buffer,function(err){ 
            if(err){console.log(err)}else{
              console.log('保存成功!')
            }
          })
    }

    @Post('edit')
    async editone(@Body() body: EditUserDTO) : Promise<UserResponse> {
        await this.userService.editone(body._id, body);
        return {
            code: 200,
            msg: 'success'
        }
    }

    @Delete(':_id')
    async deleteone(@Param('_id') _id: string) : Promise<UserResponse> {
        return {
            code: 200,
            data: await this.userService.delete(_id),
            msg: 'success'
        }
    }
}
